package com.easy.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.exception.CustomException;
import com.easy.user.mapper.HistoryMapper;
import com.easy.user.pojo.History;
import com.easy.user.service.IHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import static com.easy.common.utils.RedisConstants.*;

@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements IHistoryService {

    @Autowired
    private HistoryMapper historyMapper;

    @Resource(name = "redisTemplateHouse")
    private RedisTemplate<String, Object> historyRedisTemplate;

    @Resource(name = "redisTemplateHouse")
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${history.total}")
    private Long historyTotal;

    /**
     * 添加历史
     *
     * @param rid 房屋对象id
     * @param uid 所属用户id
     */
    @Override
    public void addHistory(Long rid, Long uid) {
        Double flag = historyRedisTemplate.opsForZSet().score(HISTORY_KEY + uid, rid);
        // 检索是否有旧记录  1.无则插入记录值  2.有则删除 再次插入
        if (flag != null) {
            // 删除旧的
            historyRedisTemplate.opsForZSet().remove(HISTORY_KEY + uid, rid);
        }
        long time = System.currentTimeMillis();
        double score = 9999999999999d - time;
        //加入新的记录，设置当前时间戳为分数score
        historyRedisTemplate.opsForZSet().add(HISTORY_KEY + uid, rid + "", score);
        //获取总记录数
        Long aLong = historyRedisTemplate.opsForZSet().zCard(HISTORY_KEY + uid);
        if (aLong > historyTotal) {
            //获取阈值200之后的记录  (0,1] 并移除
            historyRedisTemplate.opsForZSet().removeRange(HISTORY_KEY + uid, aLong - 1, aLong - 1);
        }
    }

    /**
     * 获取 浏览历史 列表
     *
     * @param page     当前页面
     * @param pageSize 页面数量
     * @param uid      uid
     * @param title    筛选值非必需
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject getHistoryList(int page, int pageSize, Long uid, String title) {
        //获取总条数
        long total = 0;
        try {
            total = historyRedisTemplate.opsForZSet().zCard(HISTORY_KEY + uid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //总页数
        long pages = total % pageSize == 0 ? total / pageSize : (total / pageSize + 1);
        //获取最大分值
        double maxScore = maxScore(HISTORY_KEY + uid);
        //获取zset的区间
        Set<Object> zSetValue = historyRedisTemplate.opsForZSet().rangeByScore(HISTORY_KEY + uid, 0, maxScore, (page - 1) * pageSize, pageSize);

        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> arr = new ArrayList<>();
        if (zSetValue != null) {
            flag:
            for (Object set : zSetValue) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", set);
                Set<Object> keys = redisTemplate.opsForHash().keys(HOUSE_CONTRACTION_KEY + set);
                for (Object key : keys) {
                    Object value = redisTemplate.opsForHash().get(HOUSE_CONTRACTION_KEY + set, key);
                    map.put((String) key, value);
                    if (key.equals("title") && title != null) {
                        if (!((String) value).contains(title)) {
                            break flag;
                        }
                    }
                }
                arr.add(map);
            }
        }
        jsonObject.put("total", Math.toIntExact(total));//总条数
        jsonObject.put("size", pageSize);//页面数量
        jsonObject.put("current", page);//当前页
        jsonObject.put("pages", pages);//总页数
        jsonObject.put("records", arr);//数据
        return jsonObject;
    }

    public Double maxScore(String name) {
        Set<Object> sortId = historyRedisTemplate.opsForZSet().reverseRange(name, 0, 0);
        if (sortId.size() == 0) {
            return 0d;
        } else {
            String hkey = String.valueOf(sortId.iterator().next());
            //根据member获得最大分值
            Double maxScore = historyRedisTemplate.opsForZSet().score(name, hkey);
            return maxScore;
        }
    }
}
